const pool = require("../base/mysql").pool,
	fs = require("fs"),
	staticPath = require('../config-local').staticPath,
	projectService = require('../project/projectService');

const sql_createShare = 'INSERT INTO `anonymous_share`(`userId`,`content`,`visitedTime`)  VALUES (?,?,?);',
	sql_getShareById = 'SELECT `content` from `anonymous_share` where id = ?;',
	sql_updateShareById = 'UPDATE `anonymous_share` set `visitedTime`=?  where id = ?;',
	sql_createShare_course = 'INSERT INTO `course_share`(`userId`,`content`)  VALUES (?,?);',
	sql_getShareById_course = 'SELECT `content` from `course_share` where id = ?;';

const createShare = (userId, content, thumbnail, cb) => {
	pool.query(sql_createShare, [userId, content, new Date()], (err, result) => {
		var ret;
		if (err) {
			ret = {
				result: -1,
				msg: "分享失败"
			};
			console.error(err);
		} else {
			var id = result.insertId;
			//创建分享缩略图
			var base64Data = thumbnail.substr("data:image/jpeg;base64,".length);
			fs.writeFile(staticPath + "/static/share/" + result.insertId.toString(16) + ".jpeg", base64Data, 'base64', (err2) => {
				console.error(err2);
			});
			ret = {
				result: 0,
				id: id,
				hexId: id.toString(16)
			}
		}
		cb(ret);
	});
};

const getShareById = (id, cb) => {
	pool.query(sql_getShareById, [id], (err, rows) => {
		var ret;
		if (err) {
			ret = {
				result: -1,
				msg: "查看分享失败"
			};
			console.error(err);
		} else if (rows.length < 1) {
			ret = {
				result: -1,
				msg: "没有此分享"
			};

		} else {
			ret = {
				result: 0,
				content: rows[0].content
			}
			//更新最后访问时间
			pool.query(sql_updateShareById, [new Date(), id], (err, result) => {
				if (err) {
					console.error(err);
				}
			});
		}
		cb(ret);
	});
};

const createCourseShareByPid = (userId, projId, cb) => {
	console.log("分享课程~");
	let ret;
	projectService.getProjById(userId, projId, (list) => {
		let content = list.content;
		let args = [userId, content];
		pool.query(sql_createShare_course, args, (err, result) => {
			if (err) {
				ret = {
					result: -1,
					msg: "分享失败"
				};
				console.error(err);
				cb(ret);
			} else {
				let id = result.insertId;
				ret = {
					result: 0,
					id: id,
					hexId: id.toString(16)
				}
				cb(ret);
			}
		});
	});
};

const getCourseShareById = (id, cb) => {
	pool.query(sql_getShareById_course, [id], (err, rows) => {
		var ret;
		if (err) {
			ret = {
				result: -1,
				msg: "查看分享失败"
			};
			console.error(err);
		} else if (rows.length < 1) {
			ret = {
				result: -1,
				msg: "没有此分享"
			};

		} else {
			ret = {
				result: 0,
				content: rows[0].content
			}
		}
		cb(ret);
	});
};

module.exports = {
	createShare,
	getShareById,
	createCourseShareByPid,
	getCourseShareById
}